package com.why.sharding.service;

import com.why.sharding.dao.OrderDao;
import com.why.sharding.dao.OrderItemDao;
import com.why.sharding.entity.Order;
import com.why.sharding.entity.OrderItem;
import com.why.sharding.util.SnowflakeIdWorker;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: wanghongyu | stan.wang@paytm.com
 * @create: 2022/01/18
 **/
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = {Exception.class})
public class OrderService {

    private final OrderDao orderDao;
    private final OrderItemDao orderItemDao;

    /**
     * 功能描述： 实现新增订单
     * @param order 订单的实体
     */
    public void saveOrder(Order order){
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(4, 2, 1L, 1L);
        order.setOrderId(snowflakeIdWorker.nextId());
        orderDao.insertSelective(order);
        order.getOrderItemList().forEach(item -> {
            item.setOrderId(order.getOrderId());
            item.setOrderItemId(snowflakeIdWorker.nextId());
            orderItemDao.insertSelective(item);
        });
    }

    /**
     * 功能描述： 根据订单ID来获取订单数据
     * @param orderId 订单流水ID
     * @return 返回查询结果
     */
    public Order getOrderByOrderId( Long orderId){
        return orderDao.queryMyOrder(orderId);
    }

    /**
     * 功能描述： 根据订单明细ID来获取订单明细数据
     * @param orderItemId 订单明细流水ID
     * @return 返回查询结果
     */
    public OrderItem getOrderItem(Long orderItemId){
        return orderItemDao.selectByPrimaryKey(orderItemId);
    }
}
